import { useState } from "react"
import { getMenuList, getMenuTree } from "api/system/menu"
import { convertTreeSelectData } from "utils/adaptation"

import { IModalProps } from "app/interfaces/system"

interface IForm {
  menuId: string
  menuName: string
  parentId: string
  orderNum: string
  path: string
  component: string
  isFrame: number
  isCache: number
  menuType: string
  visible: string
  status: string
  perms: string
  reqPath: string
  icon: string
}

export type IEditProps = IModalProps<IForm>

export function useMenu() {
  const initForm = {
    menuId: "",
    menuName: "",
    parentId: "",
    orderNum: "",
    path: "",
    component: "",
    isFrame: 0,
    isCache: 0,
    menuType: "",
    visible: "",
    status: "",
    perms: "",
    reqPath: "",
    icon: ""
  }

  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([])
  const [queryParams, setQueryParams] = useState({ menuName: "", status: "" })

  const [form, setForm] = useState(initForm)
  const [treeData, setTreeData] = useState([])
  const [modalConfig, setModalConfig] = useState({ title: "", visible: false })

  const getList = async () => {
    try {
      setLoading(true)
      const { code, data } = await getMenuList(queryParams)
      if (code === 200) {
        setDataSource(data)
      }
      setLoading(false)
    } catch (e) {
      console.log(e)
      setLoading(false)
    }
  }

  const getTree = () => {
    getMenuTree().then((res) => {
      if (res.code === 200) {
        setTreeData(convertTreeSelectData(res.data, ["menuId", "menuName"]))
      }
    })
  }

  return {
    getList,
    getTree,
    loading,
    dataSource,
    queryParams,
    setQueryParams,
    form,
    setForm,
    initForm,
    treeData,
    modalConfig,
    setModalConfig
  }
}
